package com.runjian.rundo.iot.agent.common.network.tcp.handle;

import com.runjian.rundo.iot.agent.business.publisher.DeviceMessagePublisher;
import com.runjian.rundo.iot.agent.common.codec.DeviceMessageCodec;
import com.runjian.rundo.iot.agent.common.enums.SessionIdleType;
import com.runjian.rundo.iot.agent.common.network.tcp.session.TcpDeviceSession;
import com.runjian.rundo.iot.agent.common.network.tcp.session.TcpDeviceSessionManager;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 空闲事件处理程序
 *
 * @author CaoQingHua
 */
@Slf4j
@ChannelHandler.Sharable
public class TcpIdleEventHandler extends ChannelInboundHandlerAdapter implements MessageHandler {

    private final TcpDeviceSessionManager sessionManager;

    private final DeviceMessageCodec codec;


    public TcpIdleEventHandler(TcpDeviceSessionManager sessionManager, DeviceMessageCodec codec) {
        this.sessionManager=sessionManager;
        this.codec=codec;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 检测空闲,直接关闭连接
        Boolean flag = Boolean.FALSE;
        String type = "";
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent)evt;
            TcpDeviceSession tcpDeviceSession = sessionManager.get(ctx.channel());
            if (null != tcpDeviceSession) {
                this.configTraceId(ctx);
                if (event.state() == IdleState.READER_IDLE) {
                    this.codec.idle(tcpDeviceSession, SessionIdleType.READ);
                } else if (event.state() == IdleState.WRITER_IDLE) {
                    this.codec.idle(tcpDeviceSession, SessionIdleType.WRITE);
                } else if (event.state() == IdleState.ALL_IDLE) {
                    this.codec.idle(tcpDeviceSession, SessionIdleType.ALL);
                }
            }
        }
        super.userEventTriggered(ctx, evt);
    }
}
